package com.yimi.yinhepda.views.unload_module.UnBlocking;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.pda.ym.base.MultiTypeSupport;
import com.pda.ym.entity.bean.LoadBillTaskEntity;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.adapter.RecycleAdapter.UnloadNewAdapter;
import com.yimi.yinhepda.adapter.SpinnerAdapter;
import com.pda.ym.base.CommonViewHolder;
import com.pda.ym.base.BaseTitleActivity;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.db.dao.CarPlateTableDao;
import com.yimi.yinhepda.db.dao.DepartmentTableDao;
import com.yimi.yinhepda.db.dao.UnloadTaskTableDao;
import com.yimi.yinhepda.db.dao.UnloadUcTaskNoTableDao;
import com.pda.ym.db.table.CarPlateTable;
import com.yimi.yinhepda.db.table.DepartmentTable;
import com.yimi.yinhepda.db.table.UnloadTaskTable;
import com.yimi.yinhepda.db.table.UnloadUcTaskNoTable;
import com.yimi.yinhepda.entity.bean.BaseDictEntity;
import com.pda.ym.entity.bean.CarPlanTaskEntity;
import com.pda.ym.utils.ProvinceEnum;
import com.yimi.yinhepda.entity.bean.SealOrUnsealTaskEntity;
import com.yimi.yinhepda.entity.bean.UcTaskNoVo;
import com.yimi.yinhepda.entity.request.QueryUnloadTaskRequest;
import com.yimi.yinhepda.entity.response.CarPlanTaskResponse;
import com.yimi.yinhepda.entity.response.QueryBaseDictResponse;
import com.yimi.yinhepda.entity.response.QueryUnloadTask;
import com.yimi.yinhepda.entity.response.UnBlockingResponse;
import com.pda.ym.net.NetRequest;
import com.pda.ym.utils.CarNoSelectDialog;
import com.yimi.yinhepda.event.CreateStowagesEvent;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.StringUtils;
import com.pda.ym.utils.SoundVibratorManager;
import com.yimi.yinhepda.utils.ToastUtil;
import com.yimi.yinhepda.views.createPackage_module.CreateDeptSelectActivity;
import com.yimi.yinhepda.views.load_module.CreateBranchTaskActivity;
import com.yimi.yinhepda.views.load_module.LoadUnloadGroupActivity;
import com.yimi.yinhepda.views.load_module.LoadUtil;
import com.yimi.yinhepda.views.unload_module.UnloadScanActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;

/**
 * Created by xionggaosheng on 2018/6/5.
 * 解封卸车界面
 */

public class BlockingUnloadTaskActivity extends BaseTitleActivity
        implements AdapterView.OnItemSelectedListener, CommonViewHolder.onItemCommonClickListener, TextWatcher {
    /**
     * 列表
     */
    private RecyclerView rvRightView;
    /**
     * 返回按钮
     */
    private Button ibBack;
    /**
     * 选择上一站布局
     */
    private LinearLayout llDept;
    /**
     * 点击卸车
     */
    private Button btnDetail;
    /**
     * 配载单号名
     */
    private TextView tvStowageNoName;
    /**
     * 路线选择适配器
     */
    private SpinnerAdapter<String> adapterLineType;
    /**
     * 路线集合
     */
    private List<String> lineTypelist = new ArrayList<>();
    /**
     * 网点编码
     */
    private String deptCode;
    private Map<String, String> mDeptNames = new HashMap<>();
    /**
     * 网点名称`
     */
    private String deptName;
    /**
     * 卸车列表适配器
     */
    private UnloadNewAdapter mAdapter;
    /**
     * 数据集合
     */
    private List<UnBlockingResponse.BarBillTaskEntity> dataList = new ArrayList<>();
    /**
     * 卸车任务集合
     */
    private List<CarPlanTaskEntity> mUnloadTaskist = new ArrayList<>();
    /**
     * 卸车任务
     */
    private CarPlanTaskEntity mUnloadTask;
    /**
     * 数据集合
     */
    private List<String> selectTaskList = new ArrayList<>();
    /**
     * 已经下载数据的车标号
     */
    protected ArrayList<QueryUnloadTask> downloadCarCodes = new ArrayList<>();
    /**
     * 上一站
     */
    private Set<String> preStations = new HashSet<>();
    /**
     * 下一站
     */
    private List<String> mCurrentDeptCodes = new ArrayList<>();
    /**
     * 当前
     */
    private int currentStowageIndex = 0;
    /**
     * 临时转换的车牌号
     */
    private String mTempCarNo = "";
    private SealOrUnsealTaskEntity mBarBillTaskEntity;
    /**
     * 合并卸车标志
     */
    private boolean isCombindUnload = false;
    /**
     * 创建卸车任务
     */
    private Button ibCreateUnloadTask;
    /**
     * 创建的卸车任务集合
     */
    private List<String> mCreateStowages;
    private int mSelectPlanTaskPosition = -1;

    private CarPlanTaskEntity firstPlanTask;

    /**
     * 支持多种item
     */
    private MultiTypeSupport<CarPlanTaskEntity> mMltiTypeSupport = new MultiTypeSupport() {

        @Override
        public int getLayoutId(Object item, int position) {
            if (position == 0) {
                return R.layout.view_search_laod_task;
            } else {
                return R.layout.adapter_unblocking_item_new;
            }
        }
    };

    public BlockingUnloadTaskActivity() {
        super(true);
    }

    @Override
    public int setContentViewId() {
        return R.layout.activity_un_load_new;
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        rvRightView = findViewById(R.id.rv_right_view);
        ibBack = findViewById(R.id.create_unload_task_back);
        btnDetail = findViewById(R.id.create_unload_task_arrive);
        llDept = findViewById(R.id.ll_dept);
        tvStowageNoName = findViewById(R.id.tv_stowageNo_name);
        ibCreateUnloadTask = findViewById(R.id.ib_createUnloadTask);
        ibCreateUnloadTask.setOnClickListener(this);

        if (!EventBus.getDefault().isRegistered(this)) {
            //注册事件
            EventBus.getDefault().register(this);
        }

        lineTypelist.addAll(Arrays.asList(getResources().getStringArray(R.array.line_type)));
        adapterLineType = new SpinnerAdapter<String>(this, R.layout.simple_spinner_item, lineTypelist);


        ibBack.setOnClickListener(this);
        btnDetail.setOnClickListener(this);

        //获取数据字典配置，合并卸车开关
        queryDictCombindLoadUnload();

        firstPlanTask = new CarPlanTaskEntity();

        //初始设置车牌
        List<CarPlateTable> carPlateTables = new CarPlateTableDao().getAllData();
        if (carPlateTables != null && !carPlateTables.isEmpty()) {
            firstPlanTask.setVehNo(carPlateTables.get(0).getCarPlate());
        }

        //获取解封任务跳转过来的数据
        mBarBillTaskEntity = (SealOrUnsealTaskEntity) getIntent().getSerializableExtra("task");
        if (mBarBillTaskEntity != null) {
            String carNo = mBarBillTaskEntity.getVehNo();
            if (carNo != null) {
                firstPlanTask.setVehNo(carNo);
            } else if (mBarBillTaskEntity.getBeTask() == 1) {
                //车线任务
                firstPlanTask.setNextDeptCode(mBarBillTaskEntity.getNextDeptCode());
                DepartmentTable departmentTable = new DepartmentTableDao().queryDeptByDeptCode(mBarBillTaskEntity.getNextDeptCode());
                if (departmentTable != null) {
                    firstPlanTask.setNextDeptName(departmentTable.getDeptName());
                }
            } else {
                //非车线任务
                if (mBarBillTaskEntity.getLoadTasks() != null) {
                    LoadBillTaskEntity loadTask = mBarBillTaskEntity.getLoadTasks().get(0);
                    if (loadTask.getSrcDeptCode() != null) {
                        firstPlanTask.setNextDeptCode(loadTask.getSrcDeptCode());
                        firstPlanTask.setNextDeptName(loadTask.getSrcDeptName());
                    } else {
                        showToast("解封任务没有上一站3");
                        return;
                    }
                } else {
                    showToast("解封任务没有上一站4");
                    return;
                }
            }
            firstPlanTask.setFromUnSealActivity(true);
            queryUnloadTask(mBarBillTaskEntity);
        }

        mUnloadTaskist.add(firstPlanTask);
        loadUIAdapter();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_selectNextDept:
                Intent intent = new Intent(this, CreateDeptSelectActivity.class);
                intent.putExtra("currentDept", sharedPreferUtil.getDeptCode());
                intent.putExtra("inputType", 2);
                startActivityForResult(intent, 0);
                break;
            case R.id.create_unload_task_back:
                finish();
                break;
            case R.id.iv_unblocking_detail:
                startActivity(new Intent(this, ScanBlockingActivity.class));
                break;
            case R.id.btn_carPlate:
                CarNoSelectDialog.showCarPlateDialog(this, new CarNoSelectDialog.CarNoSelectListener() {
                    @Override
                    public void onclick(String carPlate) {
                        mAdapter.getBtnCarPlate().setText(carPlate);
                        firstPlanTask.setVehNo(carPlate);
                    }
                });
                break;
            case R.id.btn_down:
                String carNo = mAdapter.getEtCarNo().getText().toString();
                String selectDept = mAdapter.getBtnSelectNextDept().getText().toString();
                if ("".equals(carNo) && "".equals(selectDept)) {
                    showToast("输入车牌号或选择上一站");
                    SoundVibratorManager.playSound(2);
                    return;
                }
                //获得卸车数据
                queryUnloadTask(null);
                break;
            case R.id.create_unload_task_arrive:
                //执行
                executeUnloadTask();
                break;
            case R.id.ib_createUnloadTask:
                //创建卸车任务
                intent = new Intent(this, CreateBranchTaskActivity.class);
                intent.putExtra(CreateBranchTaskActivity.LOAD_KEY, CreateBranchTaskActivity.UNLOAD_TYPE);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    /**
     * 查询数据字典：合并装卸车（combind_load_unload）
     */
    private void queryDictCombindLoadUnload() {
        showPgDlg("获取配置中...");
        Map<String, String> params = new HashMap<>(2);
        params.put("dictCode", "combind_load_unload");
        //查询类型，1-只查询未作废的，为null则查询所有(包含作废和未作废的)
        params.put("type", "1");

        new NetRequest().setMethod(NetRequest.Method.GET)
                .setResponsClazz(QueryBaseDictResponse.class)
                .setUrl(Constants.URL_QUERY_DICT)
                .setParams(params)
                .setConnTimeOut(10 * 1000)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        QueryBaseDictResponse response = (QueryBaseDictResponse) obj;
                        if (response != null && response.getData() != null) {
                            List<BaseDictEntity> list = response.getData();
                            for (BaseDictEntity item : list) {
                                //合并卸车部门
                                String deptCode = item.getDictValue();
                                //合并卸车开关
                                String param2 = item.getExternalParam2();
                                if (deptCode.equals(sharedPreferUtil.getDeptCode())
                                        && "1".equals(param2)) {
                                    isCombindUnload = true;
                                    return;
                                }
                            }
                        }
                        isCombindUnload = false;
                    }
                });
    }

    /**
     * 执行卸车任务
     */
    private void executeUnloadTask() {
        boolean exitSelectTask = false;
        for (CarPlanTaskEntity unLoadTask : mUnloadTaskist) {
            if (unLoadTask.isCheck()) {
                exitSelectTask = true;
            }
        }
        if (!exitSelectTask) {
            showToast("请先选择一项任务执行");
            SoundVibratorManager.playSound(2);
            return;
        }

        final List<CarPlanTaskEntity> checkList = new ArrayList<>();
        for (CarPlanTaskEntity unLoadTask : mUnloadTaskist) {
            if (unLoadTask.isCheck()) {
                checkList.add(unLoadTask);
            }
        }
        int deptType = sharedPreferUtil.getIntValue(Common.DEPT_TYPE);
        if (deptType == 5 || deptType == 6) {
            LoadUtil.toClassActivity(this, null, checkList, LoadUnloadGroupActivity.class, 2);
        } else {
            showPgDlg("添加装卸人中...");
            LoadUtil.addLoaderEmpCodes(checkList, new UICallBack() {
                @Override
                public void onError(String msg) {
                    dismissPgDlg();
                    SoundVibratorManager.playSound(2);
                    showToast(msg);
                }

                @Override
                public void onSuccess(Object obj) {
                    dismissPgDlg();
                    String task = Constants.getUUID();
                    int result = new UnloadTaskTableDao().noExitInsert(UnloadTaskTable.parseUnloadTable(task, mUnloadTaskist, 2), 2);
                    if (result >= 0) {
                        LoadUtil.toClassActivity(BlockingUnloadTaskActivity.this, task, checkList, UnloadScanActivity.class, 2);
                    } else {
                        showToast("保存卸车任务失败！");
                    }
                }
            });

        }
    }

    private void jumpToUnload() {
        String task = Constants.getUUID();
        UnloadTaskTableDao mUnloadTaskTableDao = new UnloadTaskTableDao();
        try {
            //遍历获取uc快递卸车任务号
            List<UnloadUcTaskNoTable> ucTaskNoTableList = new ArrayList<>();
            for (UnBlockingResponse.BarBillTaskEntity item : dataList) {
                if (item.isCheck()) {
                    List<UcTaskNoVo> ucTaskNoVoList = item.getUcTaskNos();
                    if (ucTaskNoVoList != null) {
                        for (UcTaskNoVo ucTaskNoVo : ucTaskNoVoList) {
                            ucTaskNoTableList.add(new UnloadUcTaskNoTable(task, ucTaskNoVo.getTaskNo(), ucTaskNoVo.getVheLineType()));
                        }
                    }
                }
            }

            if (mUnloadTaskTableDao.insert(UnloadTaskTable.parse(task, downloadCarCodes)) >= 0
                    //uc卸车任务保存
                    && new UnloadUcTaskNoTableDao().insert(ucTaskNoTableList) >= 0) {
                Intent unloadScanIntent;
                int deptType = sharedPreferUtil.getIntValue(Common.DEPT_TYPE);
                if (deptType == 5 || deptType == 6) {
                    //登录分拨，跳转至装卸组界面
                    unloadScanIntent = new Intent(this, LoadUnloadGroupActivity.class);
                } else {
                    unloadScanIntent = new Intent(this, UnloadScanActivity.class);
                }

                //unloadScanIntent = new Intent(CreateUnloadTaskActivity.this, UnloadScanActivity.class);

                Bundle bundle = new Bundle();
                //                        bundle.putString("carNo", carNo.getText().toString());
                bundle.putString("carNo", mAdapter.getBtnCarPlate().getText().toString() + mAdapter.getEtCarNo().getText().toString().toUpperCase());
                bundle.putString("task", task);
                String deptNames = "";
                for (String item : mDeptNames.values()) {
                    deptNames += item + " ";
                }
                bundle.putString("deptCode", deptNames);
                bundle.putSerializable("currentDeptCodes", (Serializable) mCurrentDeptCodes);
                //扫描类型：1-装车扫描，2=卸车扫描 ,3-离线装车，4-离线卸车,5-移库装车，6-移库卸车,7-单独移库卸车，8-分拨自提,9-跨越点货,10-融合装车，11-融合卸车
                bundle.putInt("scanType", 11);
                unloadScanIntent.putExtras(bundle);
                startActivity(unloadScanIntent);
                finish();
            } else {
                showToast("保存任务失败！");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            showToast("数据库操作失败:" + e.getMessage());
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            deptCode = data.getStringExtra("deptCode");
            deptName = data.getStringExtra("deptName");
            //选择的上一站
            mAdapter.getBtnSelectNextDept().setText(deptName);
            mAdapter.getBtnSelectNextDept().setTag(deptCode);
        }
    }

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

        //        lineType = i;

        switch (adapterView.getId()) {
            case R.id.tv_line_type:
                if (i == 0) {
                    llDept.setVisibility(View.VISIBLE);
                    tvStowageNoName.setText("任务号");
                } else {
                    llDept.setVisibility(View.GONE);
                    tvStowageNoName.setText("配载单号");
                }

                break;
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {

    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    @Override
    public void onItemClickListener(int position) {
        if (position == RecyclerView.NO_POSITION) {
            return;
        }

        mUnloadTask = mUnloadTaskist.get(position);

        if (!mUnloadTask.isCheck()) {
            List<CarPlanTaskEntity> checkTaskList = new ArrayList<>();
            for (CarPlanTaskEntity item : mUnloadTaskist) {
                if (item.isCheck()) {
                    checkTaskList.add(item);
                }
            }
            if (!isCombindUnload) {
                //是否为相同车牌号
                boolean sameCarNo = true;
                for (CarPlanTaskEntity item : checkTaskList) {
                    if (mUnloadTask.getVehNo() != null && item.getVehNo() != null) {
                        if (item.isCheck() && !mUnloadTask.getVehNo().equals(item.getVehNo())) {
                            sameCarNo = false;
                            break;
                        }
                    }
                }
                if (!sameCarNo) {
                    showToast("不可选择不同车牌号的配载单！");
                    return;
                }

                //限制干线车线任务只能选择一个
                if (mUnloadTask.getTaskNo() != null) {
                    if (mUnloadTask.getBeTask() == 1 && !checkTaskList.isEmpty()) {
                        //当前选择的是车线任务，且已有其他任务，不能合并装车
                        ToastUtil.showToast("车线任务不能合并卸车！");
                        SoundVibratorManager.playSound(2);
                        return;
                    } else {
                        //当前选择的是其他任务，且已有车线任务，不支持合并装车
                        for (CarPlanTaskEntity planTask : checkTaskList) {
                            if (planTask.getBeTask() == 1) {
                                ToastUtil.showToast("车线任务不能合并卸车！");
                                SoundVibratorManager.playSound(2);
                                return;
                            }
                        }
                    }
                }
            }

            mUnloadTask.setCheck(true);
        } else {
            mUnloadTask.setCheck(false);
        }

        notifyDataSetChanged();
    }

    @Override
    public void onItemLongClickListener(int position) {

    }

    private void queryUnloadTask(SealOrUnsealTaskEntity taskEntity) {
        queryUnloadTask(taskEntity, null);
    }

    private void queryUnloadTask(SealOrUnsealTaskEntity taskEntity, String taskNo) {
        queryUnloadTask(taskEntity, taskNo, null);
    }

    /**
     * 查询卸车任务
     */
    private void queryUnloadTask(final SealOrUnsealTaskEntity taskEntity, String taskNo, CreateStowagesEvent event) {
        QueryUnloadTaskRequest request = new QueryUnloadTaskRequest();

        if (taskEntity != null) {
            if (taskEntity.getBeTask() == 1) {
                request.setTaskNo(taskEntity.getTaskNo());
            } else if (taskEntity.getTaskNo().startsWith("P") || taskEntity.getTaskNo().startsWith("J")) {
                request.setStowageNo(taskEntity.getTaskNo());
            } else {
                if (taskEntity.getVehNo() != null) {
                    request.setCarNo(taskEntity.getVehNo());
                } else if (taskEntity.getNextDeptCode() != null) {
                    request.setDestDeptCode(taskEntity.getNextDeptCode());
                } else if (taskEntity.getLoadTasks() != null) {
                    LoadBillTaskEntity loadTask = taskEntity.getLoadTasks().get(0);
                    if (loadTask.getSrcDeptCode() != null) {
                        request.setDestDeptCode(loadTask.getSrcDeptCode());
                    } else {
                        showToast("解封任务没有上一站1");
                        SoundVibratorManager.playSound(2);
                        return;
                    }
                } else {
                    showToast("解封任务没有上一站2");
                    SoundVibratorManager.playSound(2);
                    return;
                }
            }
        } else if (event != null) {
            if (event.getCarNo() != null) {
                if (event.getCarNo().length() > 1) {
                    request.setCarNo(event.getCarNo());
                }
            }
            if (event.getNextDeptCode() != null) {
                request.setDestDeptCode(event.getNextDeptCode());
                mAdapter.getBtnSelectNextDept().setText(event.getNextDeptCodeName());
                mAdapter.getBtnSelectNextDept().setTag(event.getNextDeptCode());
            } else {
                return;
            }
        } else if (taskNo != null) {
            if (taskNo.startsWith("H")||taskNo.startsWith("J")) {
                request.setTaskNo(taskNo);
            } else {
                request.setStowageNo(taskNo);
            }
        } else {
            String carNo = mAdapter.getEtCarNo().getText().toString().toUpperCase();
            if (!"".equals(carNo)) {
                request.setCarNo(mAdapter.getBtnCarPlate().getText().toString() + carNo);
            }
            if (mAdapter.getBtnSelectNextDept().getTag() != null) {
                request.setDestDeptCode(mAdapter.getBtnSelectNextDept().getTag().toString());
            }

            if (StringUtils.isEmpty(carNo) && mAdapter.getBtnSelectNextDept().getTag() == null) {
                return;
            }
        }

        request.setSrcDeptCode(sharedPreferUtil.getDeptCode());
        request.setOperTypeCode(2);

        showPgDlg("查询中...");
        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setUrl(Constants.URL_V2_QUERY_LOAD_OR_UNLOAD_TASK)
                .setRequestObject(request)
                .setResponsClazz(CarPlanTaskResponse.class)
                .setConnTimeOut(10 * 1000)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                        SoundVibratorManager.playSound(2);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        CarPlanTaskResponse response = (CarPlanTaskResponse) obj;
                        if (response != null && response.getData() != null) {

                            for (CarPlanTaskEntity planTask : mUnloadTaskist) {
                                planTask.setCheck(false);
                            }

                            for (CarPlanTaskEntity queryTask : response.getData()) {
                                boolean hasTask = false;
                                ListIterator<CarPlanTaskEntity> it = mUnloadTaskist.listIterator();
                                while (it.hasNext()) {
                                    CarPlanTaskEntity planTask = it.next();
                                    if (planTask.getTaskNo() != null) {
                                        if (planTask.getTaskNo().equals(queryTask.getTaskNo())) {
                                            hasTask = true;
                                        }
                                    }
                                }
                                if (!hasTask) {
                                    it.add(queryTask);
                                }
                            }

                            loadUIAdapter();
                            SoundVibratorManager.playSound(1);

                            if (mCreateStowages != null) {
                                for (String stowageNo : mCreateStowages) {
                                    for (int i = 0; i < mUnloadTaskist.size(); i++) {
                                        CarPlanTaskEntity planTask = mUnloadTaskist.get(i);
                                        if (planTask.getLoadTasks() != null) {
                                            for (LoadBillTaskEntity loadTask : planTask.getLoadTasks()) {
                                                if (stowageNo.equals(loadTask.getStowageNo())) {
                                                    planTask.setCheck(true);
                                                    mSelectPlanTaskPosition = i;
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            if (mSelectPlanTaskPosition >= 0) {
                                rvRightView.scrollToPosition(mAdapter.getItemCount() - 1);
                            }

                            if (taskEntity != null && mAdapter != null) {
                                if (taskEntity.getVehNo() != null) {
                                    if (mAdapter.getBtnCarPlate()!=null){
                                        mAdapter.getBtnCarPlate().setText(taskEntity.getVehNo().substring(0, 1));
                                    }
                                }
                            }
                        } else {
                            showToast("未查询到卸车任务！");
                            SoundVibratorManager.playSound(2);
                        }
                    }
                });
    }

    private void loadUIAdapter() {
        if (mAdapter == null) {
            mAdapter = new UnloadNewAdapter(this, mUnloadTaskist, this, mMltiTypeSupport, this);
            rvRightView.setLayoutManager(new LinearLayoutManager(this));
            rvRightView.setAdapter(mAdapter);
        } else {
            notifyDataSetChanged();
        }
    }

    @Override
    protected void handleBarCode(final String result) {
        if (result == null) {
            SoundVibratorManager.playSound(2);
            showToast("条码扫描失败");
        } else {

            String palletName = StringUtils.getPalletName(result);
            if (!"".equals(palletName)) {
                mAdapter.getEtCarNo().setText(result.substring(3));
                mAdapter.getBtnCarPlate().setText(palletName);
                //获得卸车数据
                queryUnloadTask(null);
            } else {
                queryUnloadTask(null, result);
            }
        }
    }

    @Override
    public String getPageName() {
        return "卸车任务";
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        //车牌号英文字母转换成大写
        String carNo = mAdapter.getEtCarNo().getText().toString().toUpperCase();
        if (!carNo.equalsIgnoreCase(mTempCarNo)) {
            mTempCarNo = carNo;
            mAdapter.getEtCarNo().setText(carNo);
            mAdapter.getEtCarNo().setSelection(carNo.length());
        }
    }

    private void notifyDataSetChanged() {
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public boolean showBack() {
        return false;
    }

    @Override
    public void setBack() {

    }

    @NotNull
    @Override
    public String setTitle() {
        return getPageName();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMainEventBus(CreateStowagesEvent event) {
        mCreateStowages = event.getStowageNos();
        if (event.getFromActivity() == 2) {
            mUnloadTaskist.clear();
            mUnloadTaskist.add(new CarPlanTaskEntity());
            loadUIAdapter();
            queryUnloadTask(null, null, null);
        } else {
            queryUnloadTask(null, null, event);
        }
    }

}
